chown関数は、ファイルやディレクトリ(フォルダ)の所有者(owner)とグループ(group)を変更します。なお、この機能を使うには、実行プロセスが所有者やグループを変更できる権限を持っていることが必要です。
この関数は、C言語のライブラリ関数(標準関数)ではありませんので、コンパイラにより、使えない場合があります。
#include <unistd.h>
int chown(const char *path, uid_t owner, gid_t group);
*pathは変更するファイルのパス名を指定します。
ownerは所有者ID(ユーザID)を指定します。
groupはグループIDを指定します。
owner又は、groupに-1を指定すると、それらのIDは変更しません。
戻り値として、処理が成功した場合は0を、失敗した場合は-1を返します。
プログラム 例
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char ans;
int return_code = 0;
if (argc == 4) {
printf('%sの所有者を変更します。よろしいですか(y/n)==> ', *(argv + 1));
scanf('%c', &ans);
if (ans == 'y' || ans == 'Y') {
/* 所有者とグループを変更する */
if (chown(*(argv + 1), /* パス名 */
atoi(*(argv + 2)), /* 所有者ID(ユーザID) */
atoi(*(argv + 3))) == 0) { /* グループID */
printf('所有者を変更しました\n');
}
else {
printf('所有者を変更できませんでした\n');
perror('');
return_code = 1;
}
}
else {
printf('キャンセルします\n');
}
}
else {
printf('実行時引数の数が不当です\n');
return_code = 2;
}
return return_code;
}
例の実行結果
$ ls -l DIR1 合計 8 -rwxr-xr-x 1 user users 39 2008-07-29 10:13 hello_1.sh -rw-r--r-- 1 root root 39 2008-07-29 10:43 hello_2.sh $ $ ./chown.exe ./DIR1/hello_1.sh 1002 100 ./DIR1/hello_1.shの所有者を変更します。よろしいですか(y/n)==> y 所有者を変更できませんでした Operation not permitted $ $ su パスワード: # ./chown.exe ./DIR1/hello_1.sh 1002 100 ./DIR1/hello_1.shの所有者を変更します。よろしいですか(y/n)==> y 所有者を変更しました # ls -l DIR1 合計 8 -rwxr-xr-x 1 guest users 39 2008-07-29 10:13 hello_1.sh -rw-r--r-- 1 root root 39 2008-07-29 10:43 hello_2.sh $